import request from "../utils/request";
import common from "../common/index";
import constants from "../common/constants";
import envConfig from '../env';
const TextEncoding = require('text-encoding-shim');
import {
    ChatItemType,
    CreateTopicDataType,
    PhoneLoginBody, PortraitType, ResDto,
    SearchTopicDataType,
    UidDataType,
    UidPageIndexSizeType,
    UidTopicIdDataType,
    ValidateCodeBody, WxLoginBody,
    dirOpType, UidPrimaryDisciplineType
} from "../types";
export default {
    getCode: (data: ValidateCodeBody): Promise<ResDto> => request.post(`/app-api/member/auth/send-sms-code`, data),// 获取登录的手机验证码
    login: (data: PhoneLoginBody) => request.post(`/app-api/member/auth/sms-login`, data),// 登录
    wxLogin: (data: WxLoginBody) => request.post(`/app-api/member/auth/weixin-mini-app-login`, data),// 微信登录
    getUserInfo: (data: UidDataType) => request.post(`/aispire/user_info/get`, data),// 获取用户头像昵称等信息
    createPortrait: (data: PortraitType) => request.post(`/aispire/portrait/create`, data),// 用户画像创建
    getPortrait: (data: UidDataType) => request.post(`/aispire/portrait/get`, data),// 获取用户画像
    getAllSubject: (): Promise<ResDto> => request.get(`/aispire/discipline/get`, {}),// 获取一级学科列表
    getSubjectKeywords: (data: UidPrimaryDisciplineType): Promise<ResDto> => request.post(`/aispire/mobile/get_keywords`, data),// 列出所有细分领域
    getVipInfo: (): Promise<ResDto> => request.get(`/app-api/pay/vip-order/vip-verify`, {}),// 查看当前用户会员信息
    getUserStorageInfo: (data: UidDataType): Promise<ResDto> => request.post(`/aispire/user_status/storage_info`, data),// 获取用户存储空间使用情况
    getOrderList: (pageIndex: number, pageSize: number): Promise<ResDto> => request.get(`/app-api/pay/vip-order/page?pageNo=${pageIndex}&pageSize=${pageSize}`, {}),// 订单列表
    getVipProductList: (): Promise<ResDto> => request.get(`/app-api/pay/vip-order/spupage?pageNo=1&pageSize=10`, {}),// 查看当前用户会员信息
    createVipOrder: (data: {spuId: number}) => request.post(`/app-api/pay/vip-order/create`, data),// 创建购买订单
    submitVipOrder: (data: {id: string, channelCode: string, returnUrl: string, channelExtras: Object}) => request.post(`/app-api/pay/order/submit`, data),// 提交订单

    createTopic: (data: CreateTopicDataType) => request.post(`/aispire/topic/create`, data),// 创建会话
    checkUserQuota: (data: UidDataType) => request.post(`/aispire/user_status/check_user_quota`, data),// 检查用户配额是否用完
    generateParagraph: (data: any) => request.post(`/aispire/file_write/writing_paragraph`, data),// 生成段落内容
    historyTopicList: (data: UidDataType) => request.post(`/aispire/topic/list`, data),// 历史会话列表
    historyTopicDetail: (data: UidTopicIdDataType) => request.post(`/aispire/topic/display`, data),// 历史会话内容展示
    searchTopic: (data: SearchTopicDataType) => request.post(`/aispire/topic/search`, data),// 历史topic搜索
    chat: (url: string, data: any, chatItem: ChatItemType, {reasonCall, answerCall, errorCall, completeCall}: {reasonCall?: Function, answerCall?: Function, errorCall?: Function,  completeCall?: Function}) => request.stream(url, data, chatItem, {reasonCall, answerCall, errorCall, completeCall}),// 对话
    inspirationRecommend: (data: UidPageIndexSizeType) => request.post(`/aispire/inspiration/recommend`, data),// 灵感广场推荐
    getDirFileList: (data: dirOpType) => request.post(`/aispire/dir_op/list`, data),// 获取用户指定文件夹下的文件及文件夹
    academicSearch: (data: any) => request.post(`/aispire/template/academic_search`, data),// 学术搜索
    getPaperInfo: (data: any) => request.post(`/aispire/template/get_paper_info`, data),// 精准检索论文（标题/DOI）
    getInspirationDetail: (data: {uid: string, id: string}) => request.post(`/aispire/inspiration/detail_list`, data),// 获取灵感详情
    toggleCollection: (data: {id: string, action: string, uid: string, tags?: string[]}) => request.post(`/aispire/inspiration/collection`, data),// 收藏/取消收藏
    getFollowInfo: (data: {uid: string}) => request.post(`/aispire/inspiration/follow_info`, data),// 获取用户关注信息
    getCollectionList: (data: {uid: string, pageIndex: number, pageSize: number}) => request.post(`/aispire/inspiration/collection_list`, data),// 获取用户收藏列表
    inspirationSearch: (data: {uid: string, search_text: string, page_index: number, page_size: number}) => request.post(`/aispire/inspiration/search`, data),// 灵感搜索接口

    getPublishedList: (data: {uid: string, page_index: number, page_size: number}) => request.post(`/aispire/inspiration/published_list`, data),// 获取用户发布列表
    getInspirationFollowUserList: (data: {uid: string}) => request.post(`/aispire/inspiration/follow_list`, data),// 获取用户关注的用户列表
    inspirationLikeList: (data: {uid: string}) => request.post(`/aispire/inspiration/like_list`, data),// 点赞列表接口
    toggleLike: (data: {uid: string, id: string, action: string}) => request.post(`/aispire/inspiration/like`, data),// 点赞/取消点赞
    followUser: (data: {action: string, follow_uid: string, inspiration_id: string, uid: string}) => request.post(`/aispire/inspiration/follow`, data),// 关注/取消关注用户
    commentAction: (data: {uid: string, id: string, action: string, comment?: string, comment_id?: string}) => request.post(`/aispire/inspiration/comment`, data),// 评论操作（添加/删除）

    getFileUrl: (data: {uid: string, file_id: string}) => request.post(`/aispire/file_read/get_file`, data),// 根据文档id获取文档地址
    deleteFile: (data: {uid: string, file_id: string}) => request.post(`/aispire/file_op/delete`, data),// 删除文件
    fileMoveTo: (data: {uid: string, file_id: string, target_path_id: string}) => request.post(`/aispire/file_op/move`, data),// 文件移动到
    publishInspiration: (data: {uid: string, title: string, content: string, image_url: string, status: string}) => request.post(`/aispire/inspiration/publish`, data),// 发布灵感
    deleteInspiration: (data: {uid: string, id: string}) => request.post(`/aispire/inspiration/delete`, data),// 删除灵感
    // 同步文档到知识库：严格原样透传调用方传入的 data，不做任何键名或结构转换
    synchronizeDocToKnowledge: (data: any) => request.post(`/aispire/mobile/synchronize_doc_2_my_knowledge`, data),
    // 保存到灵感（保存到智库后的标记接口）
    saveInspiration: (data: {uid: string, id: string}) => request.post(`/aispire/inspiration/save`, data),
    
    // 获取AI回答时的参考资料
    getChatReference: (data: {uid: string, topic_id: string, dialogue_id: string}): Promise<ResDto> => request.post(`/aispire/topic/get_reference`, data),
    
    // 合并参考资料到聊天记录
    mergeChatReference: (data: {uid: string, topic_id: string, dialogue_id: string, body: string}): Promise<ResDto> => request.post(`/aispire/topic/merge_references`, data),
    
    // 标签管理相关接口
    getAvailableTags: (data: {uid: string}): Promise<ResDto> => request.post(`/aispire/tag/user_tags`, data), // 获取用户标签列表
    createTag: (data: {action: string, uid: number, tags: string}): Promise<ResDto> => request.post(`/aispire/tag/operation`, data), // 创建新标签
    deleteTag: (data: {action: string, uid: number, tags: string}): Promise<ResDto> => request.post(`/aispire/tag/operation`, data), // 删除标签
    renameTag: (data: {action: string, uid: number, old_tag: string, new_tag: string}): Promise<ResDto> => request.post(`/aispire/tag/operation`, data), // 重命名标签
    
    // 标签筛选相关接口
    searchByTags: (data: {uid: number, tags: string[], type: string, page_index: number, page_size: number}): Promise<ResDto> => request.post(`/aispire/inspiration/search_by_tags`, data), // 根据标签搜索内容
    
    // 为内容添加标签接口
    addTagToInspiration: (data: {action: string, id: string, uid: string, tags: string}): Promise<ResDto> => request.post(`/aispire/inspiration/tag`, data), // 为内容添加标签
    
    // 获取常用文件夹接口
    getImportantDirs: (data: {uid: string}): Promise<ResDto> => request.post(`/aispire/dir_op/important_dir`, data), // 获取常用文件夹
    
    // 获取邀请码接口
    getInvitationCode: (): Promise<ResDto> => request.get(`/app-api/pay/vip-discount/invitation-code`, {}), // 获取用户邀请码
    
    // 生成大纲接口
    generateWritingOutline: (data: {
        uid: number,
        category: string,
        idea: string,
        knowledge_base: string[],
        type: string,
        level: number,
        language: string
    }): Promise<ResDto> => request.post(`/aispire/file_write/writing_outline`, data), // 自由主题写作生成大纲
    
    generateLiteratureReviewOutline: (data: {
        uid: number,
        category: string,
        idea: string,
        dir_id: string,
        type: string,
        style: string,
        level: number,
        language: string
    }): Promise<ResDto> => request.post(`/aispire/file_write/writing_literature_review_outline`, data), // 文献综述生成大纲
    
    generateAcademicOutline: (data: {
        uid: number,
        category: string,
        idea: string,
        knowledge_base: string[],
        type: string,
        level: number,
        language: string
    }): Promise<ResDto> => request.post(`/aispire/file_write/writing_academic_outline`, data), // 学术写作生成大纲
    
    // 流式生成大纲接口
    generateOutlineStream: (url: string, data: any, {onData, onError, onComplete}: {
        onData?: (content: string, fieldType?: string) => void,
        onError?: (error: string) => void,
        onComplete?: () => void
    }) => {
        const token = common.getLocalToken()
        const headers: any = {}
        headers[constants.ApiHeaderTokenKey] = 'Bearer ' + token
        headers['Content-Type'] = 'application/json'
        headers['Accept'] = 'text/event-stream'
        
        let buffer = new Uint8Array(0)
        let jsonBuffer = ''; // 用于缓存不完整的JSON字符串
        
        const requestTask = wx.request({
            url: envConfig.apiBase + url,
            method: 'POST',
            header: headers,
            timeout: 3600000,
            data: JSON.stringify(data || {}),
            enableChunked: true,
            responseType: "arraybuffer",
            success() {
                console.log('流式请求成功完成')
                // 处理剩余的JSON缓冲区
                if (jsonBuffer.trim()) {
                    try {
                        const jsonObj = JSON.parse(jsonBuffer);
                        if (jsonObj.generating) {
                            onData && onData(jsonObj.generating, 'generating')
                        } else if (jsonObj.reasoning) {
                            onData && onData(jsonObj.reasoning, 'reasoning')
                        }
                    } catch (e) {
                        // 忽略解析失败
                    }
                }
                jsonBuffer = '';
                onComplete && onComplete()
            },
            fail(err) {
                console.error('流式请求失败:', err)
                jsonBuffer = '';
                onError && onError('请求失败: ' + err.errMsg)
            }
        })
        
        requestTask.onChunkReceived((res: {data: ArrayBuffer}) => {
            try {
                const uint8Array = new Uint8Array(res.data);
                // 合并缓冲区
                const merged = new Uint8Array(buffer.length + uint8Array.length);
                merged.set(buffer);
                merged.set(uint8Array, buffer.length);
                
                // 尝试解码
                const decoder = new TextEncoding.TextDecoder("utf-8");
                let decoded = '';
                try {
                    decoded = decoder.decode(merged, { stream: true });
                    buffer = new Uint8Array(0); // 清空缓冲区
                } catch (e) {
                    // 遇到不完整字符，保留最后4字节（最大UTF8字符长度，处理特殊符号）
                    buffer = merged.slice(-4);
                    try {
                        decoded = decoder.decode(merged.slice(0, -4), { stream: false });
                    } catch (decodeError) {
                        // 如果还是失败，尝试保留3字节
                        buffer = merged.slice(-3);
                        try {
                            decoded = decoder.decode(merged.slice(0, -3), { stream: false });
                        } catch (decodeError2) {
                            // 如果还是失败，保留全部数据
                            buffer = merged;
                            decoded = '';
                        }
                    }
                }
                
                if (!decoded) {
                    // 如果没有可解码的数据，等待更多数据
                    return;
                }
                
                // 处理 SSE 格式数据
                // 将之前未完成的JSON缓冲区和新数据合并
                const fullData = jsonBuffer + decoded;
                jsonBuffer = ''; // 清空缓冲区
                
                // 使用 split('data: ') 方式分割数据块
                const parts = fullData.split('data: ');
                
                // 第一部分可能是空的或者是之前未完成的JSON数据的一部分
                if (parts.length > 0 && parts[0].trim()) {
                    // 第一部分可能是未完成的数据，尝试添加到缓冲区
                    const firstPart = parts[0].trim();
                    if (firstPart && (firstPart.includes('{') || firstPart.includes('['))) {
                        jsonBuffer = firstPart;
                    }
                }
                
                // 处理后续的数据块
                for (let i = 1; i < parts.length; i++) {
                    let block = parts[i];
                    const isLastBlock = i === parts.length - 1;
                    
                    // 将之前的缓冲区添加到当前块的开头
                    if (jsonBuffer) {
                        block = jsonBuffer + block;
                        jsonBuffer = '';
                    }
                    
                    // 移除首尾的换行符和空白字符
                    block = block.replace(/^\n+|\n+$/g, '').trim();
                    
                    if (!block) continue;
                    
                    // 检查是否是结束标记
                    if (block === '[DONE]' || block.includes('[DONE]')) {
                        console.log('流式数据结束')
                        onComplete && onComplete()
                        continue;
                    }
                    
                    // 尝试解析JSON
                    try {
                        const jsonObj = JSON.parse(block);
                        
                        if (jsonObj.content) {
                            onData && onData(jsonObj.content, 'content')
                        } else if (jsonObj.text) {
                            onData && onData(jsonObj.text, 'text')
                        } else if (jsonObj.message) {
                            onData && onData(jsonObj.message, 'message')
                        } else if (jsonObj.data) {
                            onData && onData(jsonObj.data, 'data')
                        } else if (jsonObj.reasoning) {
                            onData && onData(jsonObj.reasoning, 'reasoning')
                        } else if (jsonObj.generating) {
                            onData && onData(jsonObj.generating, 'generating')
                        } else if (jsonObj.answer) {
                            onData && onData(jsonObj.answer, 'answer')
                        } else if (jsonObj.response) {
                            onData && onData(jsonObj.response, 'response')
                        }
                        
                        if (jsonObj.error) {
                            onError && onError(jsonObj.error)
                        }
                    } catch (parseError) {
                        // JSON解析失败，可能是数据不完整
                        // 检查是否是最后一个块，如果是，保存到缓冲区
                        if (isLastBlock) {
                            // 尝试判断是否是有效的JSON片段
                            // 检查是否包含开始标记但缺少结束标记
                            const openBraces = (block.match(/{/g) || []).length;
                            const closeBraces = (block.match(/}/g) || []).length;
                            const openBrackets = (block.match(/\[/g) || []).length;
                            const closeBrackets = (block.match(/\]/g) || []).length;
                            
                            // 如果有未匹配的开始标记，说明JSON不完整
                            if ((openBraces > closeBraces || openBrackets > closeBrackets) && block.includes('{')) {
                                jsonBuffer = block;
                            } else {
                                // 尝试查找可能的完整JSON片段
                                // 从最后一个完整的JSON对象开始
                                let lastValidJson = '';
                                let depth = 0;
                                let inString = false;
                                let escape = false;
                                
                                for (let j = 0; j < block.length; j++) {
                                    const char = block[j];
                                    if (escape) {
                                        escape = false;
                                        continue;
                                    }
                                    if (char === '\\') {
                                        escape = true;
                                        continue;
                                    }
                                    if (char === '"' && !escape) {
                                        inString = !inString;
                                    }
                                    if (!inString) {
                                        if (char === '{' || char === '[') depth++;
                                        if (char === '}' || char === ']') depth--;
                                        if (depth === 0 && (char === '}' || char === ']')) {
                                            lastValidJson = block.substring(0, j + 1);
                                            break;
                                        }
                                    }
                                }
                                
                                if (lastValidJson) {
                                    try {
                                        const jsonObj = JSON.parse(lastValidJson);
                                        if (jsonObj.generating) {
                                            onData && onData(jsonObj.generating, 'generating')
                                        } else if (jsonObj.reasoning) {
                                            onData && onData(jsonObj.reasoning, 'reasoning')
                                        } else if (jsonObj.content) {
                                            onData && onData(jsonObj.content, 'content')
                                        }
                                        // 保存剩余部分到缓冲区
                                        if (block.length > lastValidJson.length) {
                                            jsonBuffer = block.substring(lastValidJson.length).trim();
                                        }
                                    } catch (e) {
                                        // 如果还是解析失败，保存全部到缓冲区
                                        jsonBuffer = block;
                                    }
                                } else {
                                    // 无法找到完整JSON，保存全部到缓冲区
                                    jsonBuffer = block;
                                }
                            }
                        } else {
                            // 不是最后一个块，但解析失败，可能是格式问题
                            // 尝试按行分割处理
                            const lines = block.split('\n');
                            for (const line of lines) {
                                const trimmedLine = line.trim();
                                if (!trimmedLine) continue;
                                
                                try {
                                    const jsonObj = JSON.parse(trimmedLine);
                                    
                                    if (jsonObj.content) {
                                        onData && onData(jsonObj.content, 'content')
                                    } else if (jsonObj.text) {
                                        onData && onData(jsonObj.text, 'text')
                                    } else if (jsonObj.message) {
                                        onData && onData(jsonObj.message, 'message')
                                    } else if (jsonObj.data) {
                                        onData && onData(jsonObj.data, 'data')
                                    } else if (jsonObj.reasoning) {
                                        onData && onData(jsonObj.reasoning, 'reasoning')
                                    } else if (jsonObj.generating) {
                                        onData && onData(jsonObj.generating, 'generating')
                                    } else if (jsonObj.answer) {
                                        onData && onData(jsonObj.answer, 'answer')
                                    } else if (jsonObj.response) {
                                        onData && onData(jsonObj.response, 'response')
                                    }
                                    
                                    if (jsonObj.error) {
                                        onError && onError(jsonObj.error)
                                    }
                                } catch (lineError) {
                                    // 继续尝试下一行
                                }
                            }
                        }
                    }
                }
                
            } catch (e: any) {
                console.error("大纲流式数据处理异常:", e);
                // 不直接中断流，只记录错误
                // 让流继续处理后续数据
            }
        })
        
        return requestTask
    }
    ,
    // 合并论文参考文献
    mergePaperReferences: (data: {body: string, uid: number}): Promise<ResDto> => request.post(`/aispire/file_write/merge_references`, data),
    // 更改论文引用格式
    changeCitationFormat: (data: {body: string, target_format: string, uid: number}): Promise<ResDto> => request.post(`/aispire/file_write/change_citation`, data),

    // 创建笔记（用于后续保存全文）
    createNote: (data: {uid: number, file_name: string}): Promise<ResDto> => request.post(`/aispire/notes_op/create`, data),
    // 更新笔记内容（保存全文）
    updateNotes: (data: {uid: number, file_id: string, title: string, file_name: string, content: string, outline?: string, current_paragraph?: any}): Promise<ResDto> => request.post(`/aispire/notes_op/update_notes`, data)
}
